const express = require('express');
const db = require('../config/db');

const router = express.Router();

// 获取资源看板数据
router.get('/dashboard/stats', async (req, res) => {
  try {
    // 从数据库获取资源统计数据
    const [rows] = await db.execute(
      'SELECT stat_name, stat_value FROM dashboard_stats'
    );
    
    // 将结果转换为对象
    const stats = {};
    rows.forEach(row => {
      stats[row.stat_name] = row.stat_value;
    });

    res.json({
      code: 200,
      message: '获取资源统计数据成功',
      data: stats
    });
  } catch (error) {
    console.error('获取资源统计数据失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取折线图数据
router.get('/dashboard/line-chart', async (req, res) => {
  try {
    // 从数据库获取折线图数据
    const [rows] = await db.execute(
      'SELECT date_label, data_value FROM line_chart_data ORDER BY id'
    );
    
    // 分别提取标签和数据
    const labels = rows.map(row => row.date_label);
    const data = rows.map(row => row.data_value);

    res.json({
      code: 200,
      message: '获取折线图数据成功',
      data: {
        labels,
        data
      }
    });
  } catch (error) {
    console.error('获取折线图数据失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取饼图数据
router.get('/dashboard/pie-chart', async (req, res) => {
  try {
    // 从数据库获取饼图数据
    const [rows] = await db.execute(
      'SELECT category, value FROM pie_chart_data ORDER BY id'
    );
    
    // 转换为ECharts需要的格式
    const data = rows.map(row => ({
      name: row.category,
      value: row.value
    }));

    res.json({
      code: 200,
      message: '获取饼图数据成功',
      data
    });
  } catch (error) {
    console.error('获取饼图数据失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取资源列表数据
router.get('/dashboard/resources', async (req, res) => {
  try {
    const { page = 1, pageSize = 8 } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 从数据库查询资源列表
    const [rows] = await db.execute(
      'SELECT id, name, type, status, space, created_at as time FROM resources ORDER BY id LIMIT ? OFFSET ?',
      [parseInt(pageSize), parseInt(offset)]
    );
    
    // 查询总数
    const [countResult] = await db.execute('SELECT COUNT(*) as total FROM resources');
    const total = countResult[0].total;
    
    res.json({
      code: 200,
      message: '获取资源列表成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total
        }
      }
    });
  } catch (error) {
    console.error('获取资源列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 创建资源
router.post('/dashboard/resources', async (req, res) => {
  try {
    const { name, type, status, space } = req.body;
    
    // 插入新资源
    const [result] = await db.execute(
      'INSERT INTO resources (name, type, status, space) VALUES (?, ?, ?, ?)',
      [name, type, status, space]
    );
    
    res.status(201).json({
      code: 201,
      message: '创建资源成功',
      data: {
        id: result.insertId,
        name,
        type,
        status,
        space
      }
    });
  } catch (error) {
    console.error('创建资源失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 更新资源
router.put('/dashboard/resources/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, type, status, space } = req.body;
    
    // 检查资源是否存在
    const [existing] = await db.execute(
      'SELECT id FROM resources WHERE id = ?',
      [id]
    );
    
    if (existing.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '资源不存在'
      });
    }
    
    // 更新资源信息
    await db.execute(
      'UPDATE resources SET name = ?, type = ?, status = ?, space = ? WHERE id = ?',
      [name, type, status, space, id]
    );
    
    res.json({
      code: 200,
      message: '更新资源成功',
      data: {
        id: parseInt(id),
        name,
        type,
        status,
        space
      }
    });
  } catch (error) {
    console.error('更新资源失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 删除资源
router.delete('/dashboard/resources/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查资源是否存在
    const [existing] = await db.execute(
      'SELECT id FROM resources WHERE id = ?',
      [id]
    );
    
    if (existing.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '资源不存在'
      });
    }
    
    // 删除资源
    await db.execute('DELETE FROM resources WHERE id = ?', [id]);
    
    res.json({
      code: 200,
      message: '删除资源成功'
    });
  } catch (error) {
    console.error('删除资源失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;